package com.atguigu.Controller;

import com.atguigu.Serivce.UserService;
import com.atguigu.Utils.R;
import com.atguigu.Utils.ValidateCodeUtils;
import com.atguigu.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import jakarta.servlet.http.HttpSession;

import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;




@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;



    @PostMapping("sendMsg")
    public R sendMsg(HttpSession session, @RequestBody User user) {
        //获得邮箱号，相当于to
        String email=user.getPhone()+"@qq.com";
        //邮件主题，代表信息标签
        String subject="瑞吉外卖";

        if (email!=null) {//判断email是否为空
            //生成4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码为：{}",code);
            //发送内容
            String text = "【瑞吉外卖】您好，您的登录验证码为：" + code + "，请尽快登录";
            //发送
            userService.sendMsg(email,subject,text);
            //保存验证码，以便登录时验证
            session.setAttribute(email,code);
            return R.success("邮箱验证码发送成功");
        }
        return R.error("验证码发送异常，请重新发送");
    }

    @PostMapping("/login")
    public R login(HttpSession session, @RequestBody Map map) {
        //获取qq邮箱和验证码
        Object email = map.get("phone")+"@qq.com";
        Object code = map.get("code");

        //获得存放在session的验证码进行比较,不相等则提示错误
        Object attribute = session.getAttribute(email.toString());
        if (attribute.toString().equals(code.toString())) {
            //判断该用户是否为新用户，是新用户，则注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(User::getPhone, email.toString());
            User user= userService.getOne(queryWrapper);
            if (user == null) {
                //注册用户
                user = new User();
                user.setPhone(email.toString());
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }

        return R.error("验证码错误，请重输");

    }

    @PostMapping("loginout")
    public R loginout(HttpSession session) {
        session.removeAttribute("user");
        return R.success("退出登录");
    }


}
